<template>
  <div class="app-container">
    <h2 style="text-align: center">硬笔书详细添加</h2>

    <el-steps
      :active="1"
      process-status="wait"
      align-center
      style="margin-bottom: 40px"
    >
      <el-step title="添加单元课时" />
      <el-step title="添加课时内容" />
      <el-step title="添加生字学习信息" />
    </el-steps>


    <div class="block">
        <el-button type="primary" @click="addUnit();">添加单元</el-button>
        <el-dialog :title="unitTitle" :visible.sync="dialogFormVisible" :before-close="handleClose">
          <el-form ref="form" :model="form" label-width="120px" class="demo-ruleForm">
            <el-form-item label="单元名称："
              prop="name"
              :rules="[{ required: true, message: '单元名称不能为空'}]">
              <el-input
                  type="name"
                  placeholder="请输入内容"
                  v-model="form.name"
                  style="width: 50%"
                  clearable>
                </el-input>
            </el-form-item>
            <el-form-item label="重要提示："
              prop="tip"
              :rules="[{ required: true, message: '重要提示不能为空'}]">
              <el-input
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4}"
                style="width: 50%"
                placeholder="请输入内容"
                v-model="form.tip">
              </el-input>
            </el-form-item>
            <el-form-item label="单元顺序："
              prop="uorder"
              :rules="[{ required: true, message: '单元顺序不能为空'}]">
              <el-input-number v-model="form.uorder" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="insertUnit();">保 存</el-button>
          </div>
        </el-dialog>
    </div>
    <el-table
      :data="tableData"
      row-key="id"
      :expand-row-keys="expands"
      @expand-change="toggleRowExpansion"
      style="width: 100%;margin-bottom: 20px;"
      border>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            :data="props.row.datas"
            style="width: 100%">
            <el-table-column
              label="课时id"
              prop="id">
            </el-table-column>
            <el-table-column
              label="课时名称"
              prop="name">
            </el-table-column>
            <el-table-column
              label="课时页码"
              prop="page">
            </el-table-column>
            <el-table-column
              label="课时顺序"
              width="80"
              prop="corder">
            </el-table-column>
            <el-table-column
              width="400"
              label="操作">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  size="small"
                  @click="updateChapter(scope.row.id,scope.row.name,scope.row.page,scope.row.corder,scope.row.courseBook,scope.row.courseBookAudio,scope.row.courseBookPpt)"
                  >修改</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="deleteChapter(scope.row.id)"
                  >删除</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="next(scope.row.id)"
                  >添加课时图片</el-button
                >
                <el-button
                  type="text"
                  size="small"
                  @click="nextTypeface(scope.row.id)"
                  >添加生字学习</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <el-table-column
        label="单元id"
        prop="id">
      </el-table-column>
      <el-table-column
        label="单元名称"
        prop="name">
      </el-table-column>
      <el-table-column
        label="重要提示"
        prop="tip">
      </el-table-column>
      <el-table-column
        label="顺序"
        sortable
        prop="uorder">
      </el-table-column>
      <el-table-column
        label="操作">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="updateUnit(scope.row.id,scope.row.name,scope.row.uorder,scope.row.tip)"
            >修改</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="deleteUnit(scope.row.id)"
            >删除</el-button
          >
          <el-button
            type="text"
            size="small"
            @click="addchapter(scope.row.id)"
            >添加课时</el-button
          >
        <el-dialog :title="chapterTitle" :visible.sync="dialogChapterVisible" :before-close="handleCloseChapter">
          <el-form ref="chapterform" :model="chapterform" label-width="120px" class="demo-ruleForm">
            <el-form-item label="课时名称："
              prop="name"
              :rules="[{ required: true, message: '课时名称不能为空'}]">
              <el-input
                  type="name"
                  placeholder="请输入内容"
                  v-model="chapterform.name"
                  style="width: 50%"
                  clearable>
                </el-input>
            </el-form-item>
            <el-form-item label="课时页码："
              prop="page"
              :rules="[{ required: true, message: '课时页码不能为空'}]">
              <el-input-number v-model="chapterform.page" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="课时顺序："
              prop="corder"
              :rules="[{ required: true, message: '单元顺序不能为空'}]">
              <el-input-number v-model="chapterform.corder" controls-position="right" :min="0"></el-input-number>
            </el-form-item>
            <el-form-item label="教案课件："
              prop="courseBook"
              :rules="[{ required: true, message: '教案课件不能为空'}]">
              <el-upload
                class="upload-demo"
                :limit="1"
                drag
                action="http://121.41.167.195:8000/api/oss/upload"
                :file-list="fileList"
                :on-success="uploadSuccess"
                :on-exceed="uploadExceed"
                :on-remove="handleUploadRemove"
                :before-remove="beforeVodRemove"
                :before-upload="beforeTextUpload"
                >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
            <el-form-item label="教案课件音频：" prop="courseBookAudio"
              :rules="[{ required: true, message: '教案课件音频不能为空'}]">
            <el-upload
              :on-success="handleUploadCourseBookAudioSuccess"
              :on-remove="handleUploadCourseBookAudioRemove"
              :before-remove="beforeVodRemove"
              :on-exceed="handleUploadExceed"
              :file-list="fileCourseBookAudioList"
              :before-upload="beforeAudioUpload"
              :action="'http://121.41.167.195:8000/api/oss/upload'"
              :limit="1"
              class="upload-demo"
            >
              <el-button size="small" type="primary">上传音频</el-button>
              <el-tooltip placement="right-end">
                <div slot="content">
                  最大支持1G，<br />
                  支持MP3音频格式上传
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </el-upload>
            </el-form-item>
            <el-form-item label="教案课件PPT："
              prop="courseBookPpt"
              :rules="[{ required: true, message: '教案课件PPT不能为空'}]">
              <el-upload
                class="upload-demo"
                :limit="1"
                drag
                action="http://121.41.167.195:8000/api/oss/upload"
                :file-list="fileListPpt"
                :on-success="uploadPptSuccess"
                :on-exceed="uploadExceed"
                :on-remove="handleUploadRemovePpt"
                :before-remove="beforeVodRemove"
                :before-upload="beforeTextUploadPpt"
                >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="insertChapter();">保 存</el-button>
          </div>
        </el-dialog>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      expands: [],
      bid: '',
      tableData: [],
      form: {
          name: '',
          tip: '',
          uorder: '',
          updateId: '',
        },
      dialogFormVisible: false,
      chapterform: {
          name: '',
          page: '',
          corder: '',
          uid: '',
          updateId: '',
          courseBook: '',
          courseBookAudio: '',
          courseBookPpt: '',
        },
      dialogChapterVisible: false,
      fileList: [],
      fileListPpt: [],
      chapterTitle: '',
      unitTitle: '',
      fileCourseBookAudioList: [],
    };
  },
  activated() {
    this.bid = this.$route.params.id;
    this.handleChange();
  },
  methods: {
    toggleRowExpansion(row,expanded){
      this.expands = [];
      this.expands = expanded.map((item,i) =>{return item.id});//展开当前行的信息
    },
    // 上传前的钩子函数
    beforeAudioUpload(file) {
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType !== ".mp3") {
        this.$message.error("上传音频只能是mp3!");
        return false;
      }
      return true;
    },
    // 视图上传多于一个视频
    handleUploadExceed(files, fileList) {
      this.$message.warning("想要重新上传视(音)频，请先删除已上传的视(音)频");
    },
    // 教案课件音频,点击确定的时候进行彻底删除
    handleUploadCourseBookAudioRemove() {
      this.chapterform.courseBookAudio = "";
      this.fileCourseBookAudioList = [];
    },
    // 教案课件音频成功回调
    handleUploadCourseBookAudioSuccess(response, file, fileList) {
      this.chapterform.courseBookAudio = response.url;
    },
    // 上传课本之前的钩子函数
    beforeTextUpload(file){
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType !== ".pdf") {
        this.$message.error("上传教案课本只能是pdf!");
        return false;
      }
      return true;
    },
    // 上传课本之前的钩子函数
    beforeTextUploadPpt(file){
      const fileName = file.name;
      const fileType = fileName.substring(fileName.lastIndexOf("."));
      if (fileType !== ".ppt") {
        this.$message.error("上传教案课本PPT只能是PPT格式!");
        return false;
      }
      return true;
    },
    // 点击确定的时候进行彻底删除
    handleUploadRemove() {
      this.chapterform.courseBook = '';
      this.fileList = [];
    },
    // 点击确定的时候进行彻底删除教案课件ppt
    handleUploadRemovePpt() {
      this.chapterform.courseBookPpt = '';
      this.fileListPpt = [];
    },
    // 删除之前，就是点击x的时候
    beforeVodRemove(file) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    nextTypeface(id){
      this.$router.push({ path: "/yingbi/yingbiTypeface/" + id }); // chapterId
    },
    next(id){
      this.$router.push({ path: "/yingbi/yingbiChapterDetail/" + id }); // chapterId
      // 记录到哪一步了和id
      // this.$cookie.set("path", "ruanbiContentAdd");
      //this.$cookie.set("id", id);
    },
    //删除课时
    deleteChapter(id){
      this.$confirm(`确定对[课时id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbstiffchapter/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.handleChange();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //更新课时
    updateChapter(id,name,page,corder,courseBook,courseBookAudio,courseBookPpt){
      // console.log(courseBookAudio);
      this.chapterform.name = name;
      this.chapterform.page = page;
      this.chapterform.corder = corder;
      this.chapterform.updateId = id;
      this.chapterform.courseBook = courseBook;
      this.chapterform.courseBookAudio = courseBookAudio;
      this.chapterform.courseBookPpt = courseBookPpt;

      this.fileList = [];
      let obj = {};
      let filenamelist = courseBook.toString().split("/");
      obj['name'] = filenamelist[filenamelist.length-1];
      obj['url'] = courseBook;
      this.fileList.push(obj);

      if(courseBookPpt != null){
        this.fileListPpt = [];
        obj = {};
        let filenamelistPpt = courseBookPpt.toString().split("/");
        obj['name'] = filenamelistPpt[filenamelistPpt.length-1];
        obj['url'] = courseBookPpt;
        this.fileListPpt.push(obj);
      }
      if(courseBookAudio != null){
        this.fileCourseBookAudioList = [];
        obj = {};
        filenamelist = courseBookAudio.toString().split("/");
        obj['name'] = filenamelist[filenamelist.length-1];
        obj['url'] = courseBookAudio;
        this.fileCourseBookAudioList.push(obj);
      }
      this.chapterTitle = '修改课时';

      this.addchapter(id);
    },
    //添加课时
    insertChapter(){
      this.$refs["chapterform"].validate((valid) => {
        if (valid) {
          if(this.chapterform.updateId == ''){
            this.$http({
              url: this.$http.adornUrl("/sf/cbstiffchapter/save"),
              method: "post",
              data: this.$http.adornParams({
                name: this.chapterform.name,
                corder: this.chapterform.corder,
                page: this.chapterform.page,
                courseBook: this.fileList.length > 0 ? this.fileList[0].url:'',
                uid: this.chapterform.uid,
                courseBookAudio: this.chapterform.courseBookAudio,
                courseBookPpt: this.fileListPpt.length > 0 ? this.fileListPpt[0].url:'',
              }),
            }).then(({ data }) => {
              this.chapterform.name = '';
              this.chapterform.corder = '';
              this.chapterform.page = '';
              this.fileList = [];
              this.fileListPpt = [];
              this.chapterform.courseBook = '';
              this.chapterform.courseBookPpt = '';
              this.chapterform.uid = '';
              this.chapterform.courseBookAudio = '';
              this.fileCourseBookAudioList = [];
              this.dialogChapterVisible = false;
              this.$message({
                message: '添加成功!',
                type: 'success'
              });
              this.handleChange();
            });
          }else{
            this.$http({
              url: this.$http.adornUrl("/sf/cbstiffchapter/update"),
              method: "post",
              data: this.$http.adornParams({
                id: this.chapterform.updateId,
                name: this.chapterform.name,
                corder: this.chapterform.corder,
                page: this.chapterform.page,
                courseBook: this.fileList.length > 0 ? this.fileList[0].url:'',
                courseBookAudio: this.chapterform.courseBookAudio,
                courseBookPpt: this.fileListPpt.length > 0 ? this.fileListPpt[0].url:'',
              }),
            }).then(({ data }) => {
              this.chapterform.name = '';
              this.chapterform.corder = '';
              this.chapterform.page = '';
              this.fileList = [];
              this.fileListPpt = [];
              this.chapterform.courseBook = '';
              this.chapterform.courseBookPpt = '';
              this.chapterform.uid = '';
              this.chapterform.updateId = '';
              this.chapterform.courseBookAudio = '';
              this.fileCourseBookAudioList = [];
              this.dialogChapterVisible = false;
              this.$message({
                message: '修改成功!',
                type: 'success'
              });
              this.handleChange();
            });
          }
        }else{
          this.$message.error('单元名称、重要提示、顺序、教案课件、以及教案课件音频不能为空！');
        }
      });
    },
    //教案课件PPT文件上传成功
    uploadPptSuccess(response, file, fileListPpt){
      this.fileListPpt = [];
      let fileObj = {};
      let filenamelist = response.url.toString().split("/");
      fileObj['name'] = filenamelist[filenamelist.length-1];
      fileObj['url'] = response.url;
      this.fileListPpt.push(fileObj);
      this.chapterform.courseBookPpt = response.url;
    },
    //文件上传成功
    uploadSuccess(response, file, fileList){
      this.fileList = [];
      let fileObj = {};
      let filenamelist = response.url.toString().split("/");
      fileObj['name'] = filenamelist[filenamelist.length-1];
      fileObj['url'] = response.url;
      this.fileList.push(fileObj);
      this.chapterform.courseBook = response.url;
    },
    //文件上传超出数量限制
    uploadExceed(){
      this.$message({
        message: '只能上传一个文件!',
        type: 'error'
      });
    },
    //添加课时
    addchapter(uid){
      this.chapterTitle = '添加课时';
      this.chapterform.uid = uid;
      this.dialogChapterVisible = true;
    },
    handleCloseChapter(done){
      this.$confirm('确认关闭？')
        .then(_ => {
          this.chapterform.name = '';
          this.chapterform.corder = '';
          this.chapterform.page = '';
          this.fileList = [];
          this.fileListPpt = [];
          this.chapterform.uid = '';
          this.chapterform.updateId = '';
          this.chapterform.courseBook = '';
          this.chapterform.courseBookPpt = '';
          done();
        })
        .catch(_ => {});
    },
    //是否关闭模态框
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.form.name = '';
          this.form.tip = '';
          this.form.uorder = '';
          this.form.updateId = '';
          done();
        })
        .catch(_ => {});
    },
    //删除单元
    deleteUnit(id){
      this.$confirm(`确定对[单元id=${id}]进行[删除]操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          this.$http({
            url: this.$http.adornUrl("/sf/cbstiffunit/delete"),
            method: "post",
            data: this.$http.adornData([id], false),
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "删除成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.handleChange();
                },
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        })
        .catch(() => {});
    },
    //修改单元信息
    updateUnit(id,name,uorder,tip){
      this.form.name = name;
      this.form.uorder = uorder;
      this.form.tip = tip;
      this.form.updateId = id;
      this.unitTitle = '修改单元';
      this.addUnit();
    },
    //增加单元
    insertUnit(){
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if(this.form.updateId == ''){
            this.$http({
              url: this.$http.adornUrl("/sf/cbstiffunit/save"),
              method: "post",
              data: this.$http.adornParams({
                name: this.form.name,
                tip: this.form.tip,
                uorder: this.form.uorder,
                bid: this.bid,
              }),
            }).then(({ data }) => {
              this.form.name = '';
              this.form.tip = '';
              this.form.uorder = '';
              this.dialogFormVisible = false;
              this.$message({
                message: '添加成功!',
                type: 'success'
              });
              this.handleChange();
            });
          }else{
            this.$http({
              url: this.$http.adornUrl("/sf/cbstiffunit/update"),
              method: "post",
              data: this.$http.adornParams({
                id: this.form.updateId,
                name: this.form.name,
                tip: this.form.tip,
                uorder: this.form.uorder,
                bid: this.bid,
              }),
            }).then(({ data }) => {
              this.form.name = '';
              this.form.tip = '';
              this.form.uorder = '';
              this.form.updateId = '';
              this.dialogFormVisible = false;
              this.$message({
                message: '修改成功!',
                type: 'success'
              });
              this.handleChange();
            });
          }
        }else{
          this.$message.error('单元名称、重要提示以及顺序不能为空！');
        }
      });
    },
    //打开添加单元模态框
    addUnit(){
      this.unitTitle = '添加单元';
      this.dialogFormVisible = true;
    },
    //获取书本对应单元以及课时
    handleChange(){
      this.$http({
        url: this.$http.adornUrl(`/sf/cbstiffunit/getUnitsAndChapters/${this.bid}`),
        method: "get",
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.tableData = [];
          let units = data.units;
          for(var i in units){
            let firstIns = {};
            firstIns['id'] = units[i].id;
            firstIns['name'] = units[i].name;
            firstIns['tip'] = units[i].tip;
            firstIns['uorder'] = units[i].uorder;
            
            let childrens = [];
            let chapters = units[i].chapters;
            for(let j in chapters){
              let secondIns = {};
              secondIns['id'] = chapters[j].id;
              secondIns['name'] = chapters[j].name;
              secondIns['page'] = chapters[j].page;
              secondIns['corder'] = chapters[j].corder;
              secondIns['courseBook'] = chapters[j].courseBook;
              secondIns['courseBookAudio'] = chapters[j].courseBookAudio;
              secondIns['courseBookPpt'] = chapters[j].courseBookPpt;
              childrens.push(secondIns);
            }
            firstIns['datas'] = childrens;
            this.tableData.push(firstIns);
          }
        } else {
          this.tableData = [];
        }
      })
    },
  },
};
</script>
<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
